﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using OLMS.DAL;
using OLMS.BLL;

namespace OLMS.Admin
{
    public partial class AlbumsView : System.Web.UI.Page
    {
        public int AlbumId
        {
            get
            {
                if (Request["aid"] != null)
                {
                    return Convert.ToInt32(Request["aid"]);
                }
                else
                {
                    return 0;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlGenre.DataSource = GenreBLL.GetGenresList();
                ddlGenre.DataTextField = "Name";
                ddlGenre.DataValueField = "GenreId";
                ddlGenre.DataBind();
                if (AlbumId != 0)
                {
                    Albums albums = AlbumBLL.GetAlbumsById(AlbumId);
                    txtTitle.Text = albums.Title;
                    txtArtist.Text = albums.Artists.Name;
                    txtPrice.Text = string.Format("{0:C}", albums.Price);
                    fuImage.ImageUrl = albums.AlbumArtUrl;
                    ddlGenre.SelectedValue = albums.GenreId.ToString();
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            //上传文件
            if (!string.IsNullOrEmpty(fuAlbumArtUrl.FileName))
            {
                string fileName = Path.GetFileName(fuAlbumArtUrl.FileName);
                fuAlbumArtUrl.SaveAs(Server.MapPath("/Content/Images/" + fileName));

                //查询歌手ID
                int artistId = ArtistBLL.GetArtistId(txtArtist.Text);

                Albums albums = new Albums();
                albums.AlbumId = AlbumId;
                albums.ArtistId = artistId;
                albums.Title = txtTitle.Text;
                albums.Price = Convert.ToInt32(txtPrice.Text);
                albums.GenreId = Convert.ToInt32(ddlGenre.SelectedValue);
                albums.AlbumArtUrl = "/Content/Images/" + fileName;
                if (AlbumBLL.AddOrEditAlbum(albums))
                {
                    Response.Redirect("AlbumsManager.aspx");
                }
                else
                {
                    Response.Write("<script>alert('音乐专辑保存错误');</script>");
                }
            }
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("AlbumsManager.aspx");
        }
    }
}